package com.novel.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;

/**
 * 电子邮件工具类
 */
@Slf4j
@Component
public class MailUtils {

    @Resource(name = "executor")
    private Executor executor;

    private static Properties props;

    static {
        try {
            props = Resources.getResourceAsProperties("mail.properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Runnable getSendEmail(String toMail, String subject, String content) {
        return () -> {
            try {
                //获得邮件发送的Session对象
                Session session = Session.getInstance(props);
                //创建邮件发送对象
                MimeMessage message = new MimeMessage(session);
                //设置邮件发送人，即那个有邮箱去发送邮件
                message.setFrom(new InternetAddress(props.getProperty("mail.username")));
                //设置邮件要发送到那个邮箱，并指定邮件发送方式：TO 直接发送  CC抄送    BCC密送
                message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toMail));
                //设置主题
                message.setSubject(subject);
                //设置内容
                message.setText(content);
                //准备发送得到火箭
                Transport transport = session.getTransport(props.getProperty("mail.protocol"));
                //设置连接信息
                transport.connect(props.getProperty("mail.smtp.host"), props.getProperty("mail.username"), props.getProperty("mail.password"));
                //发送邮件
                transport.sendMessage(message, message.getAllRecipients());
                //关闭资源连接
                transport.close();
            } catch (Exception e) {
                log.error("邮件发送失败! toMail:{}  subject:{}   content:{}", toMail, subject, content, e);
            }
        };
    }

    /**
     * 发送邮件方法
     * 如果需要修改对应的配置文件即可
     *
     * @param toMail  邮件接收人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendEmail(String toMail, String subject, String content) {
        Runnable task = getSendEmail(toMail, subject, content);
        try {
            executor.execute(task);
        } catch (RejectedExecutionException e) {
            log.error("任务太多,被拒绝");
        } catch (Exception e) {
            log.error("线程池执行触发系统异常,请及时处理");
        }
    }

}
